const app = getApp();

Page({
  data: {
    roomNumber: '', // 从后端获取的房间号
    players: [], // 从后端获取的玩家列表
    userId: '', // 当前用户ID
    roomOwnerId: '', // 房主ID
    isReady: false, // 当前用户准备状态
    // messages: [], // 聊天消息列表
    playerCount: 0, // 当前玩家数量
    canStart: false, // 是否可以开始游戏
    isRoomOwner: false, // 是否是房主
    // messageInput: '', // 聊天输入框内容
    isOnline: true, // 添加在线状态属性
  },

  onLoad(options) {
    let roomNumber = '';
    let userId = '';
    try {
      const roomInfo = wx.getStorageSync('roomInfo');
      if (roomInfo) {
        roomNumber = roomInfo.roomNumber;
        userId = roomInfo.userId;
      } else {
        wx.showToast({
          title: '房间信息不存在',
          icon: 'none'
        });
        wx.redirectTo({
          url: '/pages/index/index'
        });
        return;
      }
    } catch (error) {
      console.error("读取roomInfo失败:", error);
      wx.showToast({
        title: '读取房间信息失败',
        icon: 'none'
      });
      wx.redirectTo({
        url: '/pages/index/index'
      });
      return;
    }
    
    this.setData({ 
      roomNumber,
      userId
    });

    // 获取房间信息而不是加入房间
    this.getRoomInfo(roomNumber);
    
    // 初始化WebSocket连接
    this.initWebSocket();
  },

  onShow() {
    // 页面显示时，更新在线状态
    this.setData({ isOnline: true });
    if (this.ws && this.ws.readyState === 1) {
      this.ws.send(JSON.stringify({
        type: 'UPDATE_ONLINE_STATUS',
        payload: {
          roomNumber: this.data.roomNumber,
          userId: this.data.userId,
          isOnline: true
        }
      }));
    }
  },

  onHide() {
    // 页面隐藏时，更新在线状态
    this.setData({ isOnline: false });
    if (this.ws && this.ws.readyState === 1) {
      this.ws.send(JSON.stringify({
        type: 'UPDATE_ONLINE_STATUS',
        payload: {
          roomNumber: this.data.roomNumber,
          userId: this.data.userId,
          isOnline: false
        }
      }));
    }
  },

  getRoomInfo(roomNumber) {
    wx.request({
      url: 'http://localhost:3000/api/room/info',
      method: 'GET',
      data: {
        roomNumber
      },
      success: (res) => {
        if (res.data && res.data.success) {
          this.updateRoomState(res.data.room);
        } else {
          wx.showToast({
            title: '获取房间信息失败',
            icon: 'none'
          });
        }
      },
      fail: (error) => {
        console.error('获取房间信息失败:', error);
        wx.showToast({
          title: '获取房间信息失败',
          icon: 'none'
        });
      }
    });
  },

  updateRoomState(room) {
    this.setData({
      players: room.players,
      playerCount: room.players.length,
      roomOwnerId: room.owner,
      isRoomOwner: room.owner === this.data.userId,
      // 检查是否所有非房主玩家都已准备
      canStart: this.data.isRoomOwner && 
                room.players.length === 3 && 
                room.players.every(p => p.id === room.owner || p.isReady)
    });
  },

  initWebSocket() {
    const wsManager = app.globalData.websocketManager;
    
    // 注册消息处理器
    wsManager.registerHandler('room', (data) => {
      this.handleWebSocketMessage(data);
    });

    // 连接并发送加入房间消息
    wsManager.connect().then(() => {
      wsManager.send({
        phase: 'ROOM_PHASE',
        type: 'JOIN_ROOM',
        payload: {
          roomNumber: this.data.roomNumber,
          userId: this.data.userId
        }
      });
    });
  },

  handleWebSocketMessage(data) {
    switch (data.type) {
      case 'ROOM_UPDATE':
        this.updateRoomState(data.payload);
        break;
      case 'ONLINE_STATUS_UPDATE':
        this.updatePlayerOnlineStatus(data.payload);
        break;
      case 'PHASE_CHANGE':
        this.changeToGame(data.payload)
      case 'ERROR':
        wx.showToast({
          title: data.payload,
          icon: 'none'
        });
        break;
    }
  },

  updatePlayerOnlineStatus(data) {
    const { userId, isOnline } = data;
    const players = this.data.players.map(player => {
      if (player.id === userId) {
        return { ...player, isOnline };
      }
      return player;
    });
    this.setData({ players });
  },

  handleGameStart() {
    if (!this.data.canStart) return;
    
    // 检查是否所有玩家都在线
    const offlinePlayers = this.data.players.filter(p => !p.isOnline);
    if (offlinePlayers.length > 0) {
      const names = offlinePlayers.map(p => p.nickname).join(', ');
      wx.showToast({
        title: `${names} 还没有回来，请稍后再试`,
        icon: 'none'
      });
      return;
    }
    
    this.ws.send(JSON.stringify({
      type: 'START_GAME',
      payload: {
        roomNumber: this.data.roomNumber
      }
    }));
  },

  handleReady() {
    const newReadyState = !this.data.isReady;
    
    this.ws.send(JSON.stringify({
      phase: 'ROOM_PHASE',
      type: 'PLAYER_READY',
      payload: {
        roomNumber: this.data.roomNumber,
        userId: this.data.userId,
        isReady: newReadyState
      }
    }));
  },

  changeToGame(payload) {
    // 1. 保存游戏信息到本地存储
    wx.setStorageSync('gameInfo', {
      roomNumber: payload.roomNumber,  // 使用roomNumber替代gameId
      gameInfo: payload.gameInfo
    });
    
    // 2. 不要关闭WebSocket连接
    
    // 3. 跳转到游戏页面，使用roomNumber作为参数
    wx.redirectTo({
      url: `/pages/game/game?roomNumber=${payload.roomNumber}`,
      success: () => {
        console.log('成功跳转到游戏页面');
      },
      fail: (error) => {
        console.error('跳转失败:', error);
        wx.showToast({
          title: '跳转游戏页面失败',
          icon: 'none'
        });
      }
    });
  },

  onUnload() {
    // 取消注册消息处理器
    app.globalData.websocketManager.unregisterHandler('room');
  }
}); 